Troubleshooting
This document provides guidance for diagnosing and resolving common issues that may arise when working with FF-API-External.
Table of Contents
Common Issues
API Connection Issues
Issue: Unable to connect to the API
Symptoms:
- HTTP 502 Bad Gateway error
- Network timeout errors
- "Connection refused" errors
Possible Causes:
- The API service is not running
- Firewall blocking connection
- Incorrect port configuration
- DNS resolution issues
- Load balancer issues
Solutions:
-
Check if the API service is running:
ps aux | grep gunicorn # If using Gunicorn
ps aux | grep uwsgi # If using uWSGI -
Verify firewall rules:
sudo iptables -L # Linux -
Verify the API is listening on the expected port:
netstat -tulpn | grep 8080 # Assuming port 8080 -
Check Nginx/Apache configuration:
nginx -t # Test Nginx configuration
apache2ctl configtest # Test Apache configuration -
Check logs for error messages:
tail -f /var/log/nginx/error.log
tail -f /var/log/apache2/error.log
tail -f /path/to/application/log
Issue: CORS Issues
Symptoms:
- Browser console showing CORS errors
- API working with direct tools like Postman but not with web applications
Solutions:
-
Verify CORS configuration in the application:
# Specific CORS setting
@app.route('/api/endpoint', methods=['GET'])
@cross_origin()
def api_endpoint():
# Implementation -
Configure CORS with more specific settings:
cors = CORS(app, resources={
r"/api/*": {
"origins": ["https://trusted-domain.com"],
"methods": ["GET", "POST"],
"allow_headers": ["Content-Type", "Authorization"]
}
})
Database Connection Issues
Issue: Unable to connect to MySQL
Symptoms:
- API returns 500 errors
- Logs showing MySQL connection errors
Possible Causes:
- Incorrect database credentials
- MySQL server not running
- Network/firewall issues
- Exceeded connection limits
Solutions:
- Verify database credentials in .env file
- Ensure MySQL server is running:
sudo systemctl status mysql - Check if you can connect to MySQL manually:
mysql -h hostname -u username -p - Check the MySQL error log:
tail -f /var/log/mysql/error.log - Verify connection limits:
SHOW VARIABLES LIKE 'max_connections';
SHOW STATUS LIKE 'Threads_connected';
Issue: Unable to connect to MongoDB
Symptoms:
- API returns 500 errors
- Logs showing MongoDB connection errors
Solutions:
- Verify MongoDB connection string in .env file
- Ensure MongoDB server is running
- Check if MongoDB certificates are correctly placed
- Try connecting to MongoDB manually:
mongo "mongodb+srv://host/database" --username user --password password - Check MongoDB logs for errors
Third-Party Service Issues
Issue: API Key or Authentication Issues
Symptoms:
- 401 or 403 errors when accessing third-party services
- Messages about invalid API keys or authentication
Solutions:
- Verify API keys in .env file
- Check if API keys have expired or been revoked
- Ensure API keys have the necessary permissions
- Check if you've reached API rate limits
- Verify that the third-party service is operational
Issue: Rate Limiting
Symptoms:
- 429 Too Many Requests errors
- Sudden failure of previously working endpoints
Solutions:
- Implement caching for frequently accessed data
- Reduce the frequency of API calls
- Implement exponential backoff and retry strategies
- Consider upgrading to a higher API tier if available
- Distribute requests across multiple API keys if possible
Performance Issues
Issue: Slow API Response Times
Symptoms:
- API calls taking longer than expected to complete
- Timeout errors
Possible Causes:
- Inefficient database queries
- Resource constraints (CPU, memory)
- Third-party service delays
- Network latency
- Lack of caching
Solutions:
-
Profile API endpoints to identify bottlenecks:
import time
start_time = time.time()
# Operation to profile
end_time = time.time()
print(f"Operation took {end_time - start_time} seconds") -
Optimize database queries:
- Add indexes to frequently queried fields
- Use query projections to return only necessary fields
- Implement pagination for large result sets
-
Implement caching for expensive operations:
# Simple in-memory cache
cache = {}
def get_data(key):
if key in cache:
return cache[key]
# Expensive operation to get data
data = expensive_operation()
cache[key] = data
return data -
Monitor resource usage:
htop # CPU and memory usage
iostat -x 1 # Disk I/O
iftop # Network I/O -
Increase server resources if necessary
Security Issues
Issue: Unusual API Access Patterns
Symptoms:
- Sudden increase in API traffic
- Access attempts from suspicious IP addresses
- Unusual endpoint access patterns
Solutions:
- Review access logs to identify suspicious patterns
- Implement rate limiting based on IP address or API key
- Consider implementing IP whitelisting for sensitive endpoints
- Review authentication mechanisms
- Enable more detailed logging for security events
Debugging Techniques
Log Analysis
The application uses Python's logging module for logging:
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
To enable more detailed logging for debugging:
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
Common log locations:
- Application logs: Configured in the application
- Nginx logs:
/var/log/nginx/access.logand/var/log/nginx/error.log - Apache logs:
/var/log/apache2/access.logand/var/log/apache2/error.log - MySQL logs:
/var/log/mysql/error.log - MongoDB logs: Configured in MongoDB configuration
API Testing
Use tools like Postman, curl, or httpie to test API endpoints:
# Using curl
curl -X GET "https://api.example.com/api/v1/endpoint" \
-H "Authorization: Bearer your_token" \
-H "Content-Type: application/json"
# Using httpie
http GET "https://api.example.com/api/v1/endpoint" \
Authorization:"Bearer your_token" \
Content-Type:"application/json"
For testing with request data:
# Using curl
curl -X POST "https://api.example.com/api/v1/endpoint" \
-H "Authorization: Bearer your_token" \
-H "Content-Type: application/json" \
-d '{"key": "value"}'
# Using httpie
http POST "https://api.example.com/api/v1/endpoint" \
Authorization:"Bearer your_token" \
key=value
Database Debugging
MySQL Debugging
Connect to MySQL and query data:
mysql -h hostname -u username -p
# Once connected
USE database_name;
SHOW TABLES;
DESCRIBE table_name;
SELECT * FROM table_name LIMIT 10;
Check for slow queries:
SHOW PROCESSLIST;
MongoDB Debugging
Connect to MongoDB and query data:
mongo "mongodb+srv://host/database" --username user --password password
# Once connected
use database_name
show collections
db.collection_name.find().limit(10)
Check for MongoDB performance:
db.currentOp()
db.serverStatus()
Common Error Codes
| HTTP Status | Meaning | Common Causes |
|---|---|---|
| 400 | Bad Request | Invalid input parameters, malformed request |
| 401 | Unauthorized | Missing or invalid authentication token |
| 403 | Forbidden | Valid authentication but insufficient permissions |
| 404 | Not Found | Resource or endpoint doesn't exist |
| 405 | Method Not Allowed | Using an unsupported HTTP method for the endpoint |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server-side error, exception in code |
| 502 | Bad Gateway | Proxy or gateway issue, API server not running |
| 503 | Service Unavailable | Server overloaded or under maintenance |
| 504 | Gateway Timeout | Timeout when the gateway server waited for the API server |
Support Resources
If you're experiencing issues not covered in this troubleshooting guide, consider the following resources:
- Check the application logs for detailed error information
- Review the documentation for the specific endpoint or feature
- Check for known issues in the issue tracker
- Consult with the development team
- For third-party service issues, consult their respective documentation and support resources
For urgent production issues, follow the incident response procedure:
- Identify the severity and impact
- Communicate the issue to the appropriate team members
- Investigate using the debugging techniques described above
- Apply temporary mitigations if possible
- Implement and test a permanent fix
- Document the incident and resolution